import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { DEFAULT_PAGE_SIZE } from '../config/contants';

import { TbUserAssets } from '../entities/TbUserAssets';

@Injectable()
export class UserAssetsModel {
  constructor(
    @InjectRepository(TbUserAssets)
    private readonly tbUserAssetsRepository: Repository<TbUserAssets>,
  ) {}

  // 查询用户资产列表
  async getUserAssetsList(
    userId: number,
    limit: number,
    offset: number,
  ): Promise<[TbUserAssets[], number]> {
    if (!offset || offset < 0) {
      offset = 0;
    }

    if (!limit || limit < 1) {
      limit = DEFAULT_PAGE_SIZE;
    }

    let where: any = { userId };

    return await this.tbUserAssetsRepository.findAndCount({
      where,
      skip: offset,
      take: limit,
      order: {
        id: 'DESC',
      },
    });
  }

  // 查询用户资产详情
  async getUserAssetsByUserId(userId: number): Promise<TbUserAssets> {
    return await this.tbUserAssetsRepository.findOne({
      where: {
        userId,
      },
    });
  }

  async searchUserAssets(
    userId: number,
    assetAddress: string,
    assetType: number,
    tokenId: number,
  ): Promise<TbUserAssets> {
    let where: any = {
      userId,
    };
    if (assetAddress != '') {
      where.assetAddress = assetAddress;
    }
    if (assetType > 0) {
      where.assetType = assetType;
    }
    if (assetType > 0) {
      where.tokenId = tokenId;
    }
    return await this.tbUserAssetsRepository.findOne({
      where,
      order: {
        id: 'DESC',
      },
    });
  }

  // 增加或保存用户资产
  async saveUserAssets(
    data: any,
    manager: EntityManager = null,
  ): Promise<TbUserAssets> {
    if (!data.id || data.id == 0) {
      data.createdAt = new Date();
    }
    data.updatedAt = new Date();

    try {
      if (manager) {
        return await manager.save(data); // 便于在事务中执行
      } else {
        return await this.tbUserAssetsRepository.save(data);
      }
    } catch (error) {
      console.error('saveUserAssets error:', error);
      throw error;
    }

    // 执行原生sql
    // await this.tbUserAssetsRepository.query('UPDATE tb_user_assets SET asset_address='0x...' where id=1');
  }
}
